# coding:utf-8
# __user__ = hiicy redldw
# __time__ = 2019/8/8
# __file__ = __init__.py
# __desc__ =
# 先看看解码
# 解码回坐标
import pandas as pd
from scipy import misc
import numpy as np
import cv2
import matplotlib.pyplot as plt

__all__ = ['decode_img_pixel']
# image = r'f:\Resources\kdata\severstal-steel-defect-detection\train_images\00cdb56a0.jpg'
# ftrain = r'f:\Resources\kdata\severstal-steel-defect-detection\train.csv'
# data = pd.read_csv(ftrain)
# img = cv2.imread(image)
# h, w = img.shape[:2]


# 解码:变为坐标
def decode_img_pixel(pixels, h, w):
    if type(pixels) is not str:
        return (-1, -1)
    pixels = pixels.split(" ")
    pixelems = [(int(pixels[pixel]),int(pixels[pixel + 1])) for pixel in range(0, len(pixels), 2)]
    pixeles = [[pixeltuple[0] + i for i in range(pixeltuple[1])] for pixeltuple in pixelems]
    totpix = h * w

    def decode(pixel):
        shang = int(pixel / h)
        yu = pixel % h
        if yu == 0:
            x1 = shang
            y1 = h
        else:
            x1 = shang + yu
            y1 = yu
        return (x1 - 1, y1 - 1)
    pixelemes = []
    for pixelem in pixeles:
        pix = []
        for pel in pixelem:
            pix.append(decode(pel))
        pixelemes.append(pix)
    return pixelemes


# dtemp = data.set_index("ImageId_ClassId")

# data.loc[data['ImageId_ClassId'].fillna("").str.contains("00cdb56a0")]
# print(ep[0].split(" "))

# df:pd.DataFrame = data.loc[data['ImageId_ClassId'].fillna("").str.contains("00cdb56a0")]
# df['EncodedPixels'] = df['EncodedPixels'].apply(decode_img_pixel, args=(h, w))
# df.reset_index(inplace=True)
# print(df)
# ep182 = df.loc[2,'EncodedPixels']
# ep1 = ep182[2]
#
# ep1 = np.array(ep1,dtype=np.int32)
# out = cv2.approxPolyDP(ep1,epsilon=0.5,closed=True)
# cv2.polylines(img,ep182,1,(0,255,0),20) # 画多边形
# # cv2.fillPoly()
# print(ep1)
# print('-'*10,'\n')
# print(out)
# plt.imshow(img)
# plt.show()
"""
import tensorflow as tf
frozen_model_filename = r"f:\Resources\kdata\severstal-steel-defect-detection\model\deeplabv3_cityscapes_train\frozen_inference_graph.pb"

    # We load the protobuf file from the disk and parse it to retrieve the
    # unserialized graph_def
with tf.gfile.GFile(frozen_model_filename, "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

    #saver=tf.train.Saver()
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(
            graph_def,
            input_map=None,
            return_elements=None,
            name="prefix",
            op_dict=None,
            producer_op_list=None
        )
        sess = tf.Session(graph=graph)
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
        saver=tf.train.Saver()
        save_path = saver.save(sess, "f:\Resources\kdata\severstal-steel-defect-detection\model/model.ckpt")
        print("Model saved to chkp format")
        """

pi = r'F:\Resources\kdata\severstal-steel-defect-detection\segmentation_results\000123_prediction.png'
img = misc.imread(pi)
im = img != 0
print(im.shape,np.count_nonzero(im))
print(img*im)